package com.example.elm.StoreAndGoods

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.elm.CartAndOrder.CartMainFragment
import com.example.elm.Public.CartGoodsInfo
import com.example.elm.Public.GoodsInfo
import com.example.elm.Public.MyApplication
import com.example.elm.R
import com.example.elm.databinding.GoodsChooseBinding
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class GoodsChooseActivity : ComponentActivity() {
    private  lateinit var binding: GoodsChooseBinding
    private lateinit var  startForResult: ActivityResultLauncher<Intent>
    private val server_ip = MyApplication.serverIp
    private var maxId = MyApplication.maxId
    private var info = "微辣"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = GoodsChooseBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //获取数据
        val GoodData = intent.getSerializableExtra("good_data") as GoodsInfo
        //填充数据
        binding.a1.text = GoodData.name
        binding.a5.text = "￥"+"${GoodData.price}"
        val imageResid = this.resources.getIdentifier(
            GoodData.image,"drawable",this.packageName
        )
        if (imageResid != 0) {
            binding.a4.setImageResource(imageResid)
        } else {
            binding.a4.setImageResource(R.drawable.aa1)
        }

        val checkBox1= binding.checkBox1
        val checkBox2= binding.checkBox2
        val checkBox3= binding.checkBox3

        // 设置默认选中
        checkBox1.isChecked = true

        val checkBoxList = listOf(checkBox1,checkBox2,checkBox3)

        checkBoxList.forEach { checkBox ->
            checkBox.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    info = checkBox.text.toString()
                    Log.d("MAXID在GoodChoose中Add", "${info}")
                    // 取消其他 CheckBox 的选中状态
                    checkBoxList.forEach { otherCheckBox ->
                        if (otherCheckBox != checkBox) {
                            otherCheckBox.isChecked = false
                        }
                    }
                }
            }
        }
        //减份数
        binding.goodDecrease.setOnClickListener {
            var count = binding.goodCount.text.toString().toIntOrNull()?:1
            if (count > 1) {
                binding.goodCount.text = "${count-1}"
            } else {
                Toast.makeText(this, "已是最小份数：1",Toast.LENGTH_SHORT).show()
            }
        }
        //加份数
        binding.goodIncrease.setOnClickListener {
            var count = binding.goodCount.text.toString().toIntOrNull()?:1
            binding.goodCount.text = "${count+1}"
        }

        // 注册ActivityResultLauncher,用来接收从CartMainFragment返回的结果
        startForResult = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            Log.d("ActivityResult", "Received result with code: ${result.resultCode}")
            if (result.resultCode == Activity.RESULT_OK) {
                //接收从AddressActivity返回的结果
                val updatedAddressData = result.data?.getStringExtra("address_data")
                Log.d("ActivityResult", "Returned Address: $updatedAddressData") // 检查返回值
                updatedAddressData?.let {
                    //binding.tvAddress.text = it
                }
            }
        }
        //点击入购物车
        binding.addToCart.setOnClickListener {
            val count = binding.goodCount.toString().toIntOrNull()?:1
            val CartGoodsData = CartGoodsInfo(GoodData.image, GoodData.store, GoodData.price, GoodData.name, info, count,maxId+1)
            Log.d("MAXID在GoodChoose中Add", "${info}")
            maxId = maxId + 1
            MyApplication.maxId = maxId
            Log.d("MAXID在GoodChoose中", "${maxId}")
            addGoodsToCartPost(CartGoodsData)
            finish()
        }

        binding.fanhui.setOnClickListener{
            finish()
        }
    }

    // 新增数据（post附加数据）
    fun addGoodsToCartPost(cartGoodsInfo: CartGoodsInfo){
        val add_goods_jsp = "http://$server_ip:8080/CartAndOrder/add_CartGoods.jsp"
        thread {
            var connection : HttpURLConnection ? = null
            try {
                val response = StringBuilder()
                val url = URL(add_goods_jsp)
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 8000 //  连接 超时
                connection.readTimeout = 8000 // read 超时时间
                connection.requestMethod = "POST"
                connection.setRequestProperty("Accept-Charset", "UTF-8")
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                val output = DataOutputStream(connection.outputStream)
                val paraStr = "&image=${cartGoodsInfo.image}&store=${cartGoodsInfo.store}&price=${cartGoodsInfo.price}&name=${cartGoodsInfo.name}&info=${cartGoodsInfo.info}&count=${cartGoodsInfo.count}&id=${cartGoodsInfo.id}"
                output.write(paraStr.toByteArray())
                val input = connection.inputStream
                //  读取输入流，类似与文件流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use{
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                showResponse(response.toString())
            }
            catch (e: Exception){
                e.printStackTrace()
            }
            finally {
                connection?.disconnect()
            }
        }
    }
    fun showResponse(response:String){
        runOnUiThread{
            Toast.makeText(this, response,Toast.LENGTH_SHORT).show()
        }

    }


}